package json.jackson;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import json.jackson.entity.Car;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName JacksonUtils
 * @Description TODO
 * @Author KunxianLi
 * Date 2021/9/10 15:18
 * Version 1.0
 **/
public class JacksonUtils {

    public static void main(String[] args) {

        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 1. objectMapper.readValue json字符串转对象
//            String carJson ="{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
//            Car car = objectMapper.readValue(carJson, Car.class);
//            System.out.println("car brand:"+car.getBrand()+";car doors:"+car.getDoors());

            // 2.objectMapper.writeValueAsString  对象转json字符串
//            Car carObject = new Car();
//            carObject.setBrand("BMW");
//            carObject.setDoors(4);
//            String carStr = objectMapper.writeValueAsString(carObject);
//            System.out.println(carStr);

            /**
             *  序列化和反序列化的定义：
             *    (1)Java序列化就是指把Java对象转换为字节序列的过程
             *    (2)Java反序列化就是指把字节序列恢复为Java对象的过程。
             **/
            //objectMapper.configure 可以用来自定义一些反序列化/序列化的策略
            //1. 反序列化策略：DeserializationFeature
//            1.1 FAIL_ON_UNKNOWN_PROPERTIES 当有未知字段时，是否报错  true：报错，false：不报错
//            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,true);
////            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
//            String carJson ="{ \"brand\" : \"Mercedes\", \"doors\" : 5,\"test\":1 }";
//            Car car = objectMapper.readValue(carJson, Car.class);
//            System.out.println("car brand:"+car.getBrand()+";car doors:"+car.getDoors());

            // 默认日期类型转成字符串时是：Date–>long
            Car carObject = new Car();
            carObject.setBrand("BMW");
            carObject.setDoors(4);
            carObject.setDate(new Date());
            String carStr = objectMapper.writeValueAsString(carObject);
            System.out.println(carStr);

        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
